package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/octet-stream");
        String file = req.getParameter("file");
        resp.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(file, StandardCharsets.UTF_8));
        String dir = "F:\\kaifamiao.1\\JavaWeb\\temp\\upload";
        String path = dir + File.separator + file;
        FileInputStream fileInputStream = new FileInputStream(path);
        ServletOutputStream outputStream = resp.getOutputStream();
        fileInputStream.transferTo(outputStream);
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }
}
